package com.wwk.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wwk.constant.RedisConstant;
import com.wwk.dao.CheckMealDao;
import com.wwk.entity.PageResult;
import com.wwk.entity.QueryPageBean;
import com.wwk.pojo.Setmeal;
import com.wwk.service.CheckMealService;
import freemarker.core.ParseException;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname CheckMealServiceImpl
 * @Description TODO
 * @Date 2020/11/1 21:03
 * @Created by com.wwk
 * @Author com.wwk
 */
@Service(interfaceClass = CheckMealService.class)
@Transactional
public class CheckMealServiceImpl implements CheckMealService {

    @Autowired
    private CheckMealDao mealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    private String out_put_path="D:\\apache-maven_项目\\A-Health\\health_parent\\health-mobile\\src\\main\\webapp\\pages";

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //添加要添加套餐信息，
        mealDao.addMeal(setmeal);
        //还要向多对多表中添加检查组的内容
        addMealGroup(setmeal.getId(), checkgroupIds);

        //将图片名称保存到Redis
        savePic2Redis(setmeal.getImg());
    }

    //将图片名称保存到Redis
    private void savePic2Redis(String pic) {
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, pic);
        //新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }

    @Override
    public void delete(Integer mealId) {
        //先删除关联表
        mealDao.deleteMealGroups(mealId);
        //再删除套餐表
        mealDao.deleteMealById(mealId);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Setmeal> pages = mealDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(pages.getTotal(), pages.getResult());
    }

    public void addMealGroup(Integer mealId, Integer[] checkgroupIds) {
        Map<String, Integer> map;
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer groupId : checkgroupIds) {
                map = new HashMap<>();
                map.put("setmeal_id", mealId);
                map.put("checkgroup_id", groupId);
                mealDao.addMealGroup(map);
            }
        }

    }

    @Override
    public List<Setmeal> findAll() {
        return mealDao.findAll();
    }

    @Override
    public Setmeal findById(int id) {
        return mealDao.findById(id);
    }

    //生成静态页面
    public void generateMobileStaticHtml() {
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = this.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", dataMap);
    }

    //生成套餐详情静态页面（多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("setmeal", this.findById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", dataMap);
        }
    }

    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            // 加载模版文件
            Template template = configuration.getTemplate(templateName);
            // 生成数据
            File docFile = new File(out_put_path+ "\\" + htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            template.process(dataMap,out);
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            try{
                if (null!=out){
                    out.flush();
                }
            }catch (Exception e1){
                e1.printStackTrace();
            }
        }
    }
}